﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Core.Interface;
using System.Configuration;
using PServiceBus.Core.Runtime;
using PServiceBus.Core.Logger;
using Phoenix.ReflectionExtensions;
using PServiceBus.Core.Configuration;
using PServiceBus.Core.Runtime.Configuration;

namespace PServiceBus.Core.Manager {
    public class ObserverManager {
        private static Dictionary<Type, IList<IObserver>> _observers;
        private static readonly Type _subscriberType = typeof(ISubscriberObserver);
        private static readonly Type _topicType = typeof(ITopicObserver);
        private static Dictionary<Type, IList<IObserver>> Observers {
            get {
                if (_observers == null) {
                    _observers = new Dictionary<Type, IList<IObserver>>();
                    foreach (var observerConfig in ConfigurationProvider.ObserverConfigs) {
                        var ex = MethodHelper.Try(() =>
                        {
                            var observer = DynamicBroker.Broker[observerConfig.Type].New() as IObserver;
                            var type = observerConfig.ObserverType == ObserverConfigType.Topic ? _topicType : _subscriberType;
                            observer.Address = observerConfig.Address;
                            observer.Interval = observerConfig.Interval;
                            if (!_observers.ContainsKey(type)) _observers[type] = new List<IObserver>();
                            _observers[type].Add(observer);
                        });
                        ESBLogger.Log(ex);
                    }
                }
                return _observers;
            }
        }
        internal static IEnumerable<IObserver> GetObservers<TObserver>() where TObserver : IObserver {
            var type = typeof(TObserver);
            return Observers.ContainsKey(type) ? Observers[type] : new List<IObserver>();
        }
    }
}
